import React from 'react'
import { Form, Input, Button, message } from 'antd'
import '@/less/login.less'
import logoImgSrc from '@/assets/images/logo.png'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { RegisterApi } from '@/request/api'
import { useNavigate } from 'react-router-dom'

export default function Register() {
  const navigate = useNavigate()
  const onFinish = values => {
    let { username, password } = values
    let p = { username, password }
    RegisterApi(p).then(res => {
      message.success(res.message)
      setTimeout(() => navigate('/login'), 1500)
    })
  }

  return (
    <div className="login">
      <div className="login-form">
        <img className="logo-img" src={logoImgSrc} alt="" />
        <Form
          name="basic"
          initialValues={{
            remember: true
          }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            rules={[
              {
                required: true,
                message: '请输入用户名'
              }
            ]}
          >
            <Input
              prefix={<UserOutlined className="site-form-item-icon" />}
              placeholder="请输入用户名"
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码'
              }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined className="site-form-item-icon" />}
              placeholder="请输入密码"
              size="large"
            />
          </Form.Item>
          <Form.Item
            name="confirm"
            dependencies={['password']}
            hasFeedback
            rules={[
              {
                required: true,
                message: '请输入密码'
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve()
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'))
                }
              })
            ]}
          >
            <Input.Password
              size="large"
              placeholder="请再次输入密码"
              prefix={<LockOutlined className="site-form-item-icon" />}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block size="large">
              注册
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
